package com.my.dao.impl;

import java.math.BigInteger;
import java.util.List;

import com.my.bean.Admin;
import com.my.dao.AdminDAO;
import com.my.dao.IBaseDAO;

public class AdminDAOImpl implements AdminDAO {
	private IBaseDAO<Admin> basedao;

	public void setBasedao(IBaseDAO<Admin> basedao) {
		this.basedao = basedao;
	}

	@Override
	public Admin checkLogin(Admin admin) {
		String hql = "from Admin as a where a.name=? and a.pass=? and a.role.id = ?";
		String name = admin.getName();
		String pass = admin.getPass();
		String roleId = admin.getRole().getId().toString();
		return basedao.checkEntity(hql, name, pass, roleId);
	}

	@Override
	public boolean isExist(String name) {
		if (name.isEmpty()) {
			return false;
		}
		String hql = "from Admin as a where a.name=?";
		return basedao.isExist(hql, name);
	}

	@Override
	public boolean addAdmin(Admin admin) throws Exception {
		if (this.checkAdmin(admin)) {
			return basedao.add(admin);
		}
		return false;
	}

	@Override
	public boolean editAdmin(Admin admin) throws Exception {
		if (this.checkAdmin(admin)) {
			return basedao.edit(admin);
		}
		return false;
	}

	@Override
	public Admin getAdminById(Class<Admin> c, Integer id) throws Exception {
		return basedao.getById(c, id);
	}

	@Override
	public boolean removeAdmin(Integer id) throws Exception {
		Admin admin = basedao.getById(Admin.class, id);
		if (admin != null) {
			basedao.remove(admin);
		}
		return false;
	}

	@Override
	public BigInteger getTotalAdminRecords() throws Exception {
		String sql = "select count(admin_id) from info_admin";
		return basedao.getTotalRecords(sql);
	}

	@Override
	public List<Admin> getAllAdminByPage(int pageindex, int pagesize)
			throws Exception {
		String hql = "from Admin";
		return basedao.getAllEntityByPage(hql, pageindex, pagesize);
	}

	@Override
	public BigInteger searchTotalAdminRecords(Admin admin) throws Exception {
		String sql = "select count(admin_id) from info_admin where admin_name like ?";
		String item1 = admin.getName() + "%";
		return basedao.getTotalRecords(sql, item1);
	}

	@Override
	public List<Admin> searchAdminByPage(int pageindex, int pagesize,
			Admin admin) throws Exception {
		String hql = "from Admin as a where a.name like ?";
		String item1 = admin.getName() + "%";
		return basedao.getAllEntityByPage(hql, pageindex, pagesize, item1);
	}

	boolean checkAdmin(Admin admin) {
		if (admin == null || admin.getName().isEmpty()) {
			return false;
		} else {
			return true;
		}
	}
}
